﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Media;

namespace FierceWar
{
	public class MenuScreen : Screen
	{
		private static Random _random = new Random();
		private static List<int> _songIndexes = new List<int>();

		public MenuScreen(
			GameResources resources, List<EventHandler> screenEvents)
			: base(resources, screenEvents)
		{
		}

		public MenuScreen(
			GameResources resources, EventHandler screenEvent)
			: base(resources, screenEvent)
		{
		}

		public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
		{
			base.Update(gameTime);
			SmartPlay();
		}

		public override void Reset()
		{
			base.Reset();
			if (_songIndexes.Count == 0)
			{
				for (int i = 0; i < Resources.MainMenuBackground.Count; i++)
				{
					_songIndexes.Add(i);
				} 
			}
		}

		public override void PlayMusic()
		{
			base.PlayMusic();

			MediaPlayer.Volume = 1.0f;
			MediaPlayer.IsRepeating = false;
			SmartPlay();
		}

		private void SmartPlay()
		{
			if (MediaPlayer.State == MediaState.Stopped)
			{
				if (_songIndexes.Count == 0)
				{
					Reset();
				}
				MediaPlayer.Play(NextSong());
			}
		}

		private Song NextSong()
		{
			int songIdx = _random.Next(_songIndexes.Count);
			Song nextSong = Resources.MainMenuBackground[_songIndexes[songIdx]];
			_songIndexes.RemoveAt(songIdx);

			return nextSong;
		}
	}
}
